(function ($) {
  // All modals
  $.fn.modal.Constructor.Default.backdrop = 'static';

  // Notification Button Focus
  $('.modal').on('shown.bs.modal', function () {

    var $self = $(this);

    if ($(this).hasClass('secondChance')) {
      $($self)
        .attr('aria-hidden', 'false')
        .attr('aria-live', 'polite');
    };


    $('.modal .btn-primary').focus();
    if (!$('body').hasClass('modal-open')) {
      $('body').addClass('modal-open');
    }
  });

  // Notification Winner aria helper
  $("[id^='modalSubmit-notificationWinner']").on('click', function () {
    $(this)
      .parents('.modal')
      .attr('aria-hidden', 'true');
  })

  // Modal Deactivation Form Radio Check Submit
  $('#cancellation-yes-button').on('click', function () {
    $('#btn--deactivation').attr('disabled', true);
  });

  $('input[name="CancelReason"]').on('click', function () {
    if (!$('input[name="CancelReason"]').is(':checked')) {
      $('#btn--deactivation').attr('disabled', true);
    } else {
      $('#btn--deactivation').attr('disabled', false);
    }
  });

  $('#cancellation-modal').on('hidden.bs.modal', function () {
    // Check body for class modal-open
    if (!$('body').hasClass('modal-open')) {
      $('body').addClass('modal-open');
      $('body').attr("style", "overflow:auto");
    }
  });

  $('[data-secondchance-notification]').on('hidden.bs.modal', function () {
    //Grab the notificationID from the attribute;
    var notificationId = $(this).data('secondchance-notification');

    //fire off a request to the server to acknowledge the notification.
    $.ajax({
      url: '/api/Sitecore/Notification/AcknowledgeNotification',
      type: 'GET',
      dataType: 'json',
      data: {
        notificationId: notificationId
      },
      success: function (data) {}, //We really don't care if we succeed or fail at this point.
      error: function (xhr, ajaxOptions, thrownError) {}
    });

  });

  // Session Timeout Modal Functions
  var modaltimed = $('.modal.timed');
  var modalnow = $('.modal.now');
  var modalactions = $('.modal.actions');
  var actiontime = $('.secondary-action').data('action-time');
  var secondchance = $('.modal.secondChance');

  function action() {
    if ($('.secondary-action').hasClass('close')) {
      $(modalactions).modal('hide');
    }
    if ($('.secondary-action').hasClass('link')) {
      $('#modalSecondaryButton')[0].click();
    }
    console.log(actiontime);
  }

  if (modalnow.length > 0) {
    $(modalnow).modal('show');
  }

  if (modaltimed.length > 0) {
    setTimeout(function () {
      $(modaltimed).modal('show');
    }, $(modaltimed).data('notification-time'));
  }

  if (modalactions.length > 0) {
    $.each($(modalactions), function () {
      setTimeout(function () {
        $(modalactions).modal('show');
        console.log($(modalactions).data('notification-time'));
        setTimeout(action, actiontime);
      }, $(modalactions).data('notification-time'));
    });
  }

  if (secondchance.length > 0) {
    setTimeout(function () {
      $('.modal[id*=1]').modal('show');
    }, 3000);
    $('.modal[id*=1] .btn').focus();

  }

  // Cookie functions from w3schools
  function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  // Set Cookie with Modal 
  var cookieName = $(".notification.cookie").data("notification-name");
  var cookieValue = $(".notification.cookie").data("notification-value");
  var cookieExpiration = $(".notification.cookie").data("notification-expiration");
  var cookieid = $(".notification").data("notification-id");
  $(".notification").on("hidden.bs.modal", function (e) {
    if ($(this).hasClass('cookie')) {
      setCookie(cookieName, cookieValue, cookieExpiration);
      console.log(cookieName);
    }
  });


  // Focus Trap in Modals
  var itsatrap = function (elem) {
    var tabbable = elem.find('select, input, textarea, button, a').filter(':visible');
    var firstTabbable = tabbable.first();
    var lastTabbable = tabbable.last();

    /*set focus on first input*/
    // firstTabbable.focus();

    /*redirect last tab to first input*/
    lastTabbable.on('keydown', function (e) {
      if ((e.which === 9 && !e.shiftKey)) {
        e.preventDefault();
        firstTabbable.focus();
      }
    });

    /*redirect first shift+tab to last input*/
    firstTabbable.on('keydown', function (e) {
      if ((e.which === 9 && e.shiftKey)) {
        e.preventDefault();
        lastTabbable.focus();
      }
    });

    /* allow escape key to close insiders div */
    elem.on('keyup', function (e) {
      if (e.keyCode === 27) {
        elem.hide();
      }
    });

  };
  $('.modal').on('shown.bs.modal', function () {
    itsatrap($('.modal'));
  });


})(jQuery);